package com.android.lovely.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.android.lovely.databinding.AdapterLoadingFooterBinding

class DetailLoadAdapter(private val loadMoreBinding: AdapterLoadingFooterBinding) : RecyclerView.Adapter<DetailLoadAdapter.LoadMoreHolder>() {

    class LoadMoreHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    var onLoadMoreListener: (() -> Unit)? = null

    var isLoading = false
        set(value) {
            field = value
            if (value) {
                loadMoreBinding.error.isVisible = false
                loadMoreBinding.loading.isVisible = true
                loadMoreBinding.nomore.isVisible = false
            }
        }

    var loadMoreEnd = false
        set(value) {
            field = value
            if (value) {
                loadMoreBinding.error.isVisible = false
                loadMoreBinding.loading.isVisible = false
                loadMoreBinding.nomore.isVisible = true
            }
        }

    fun allHide() {
        loadMoreBinding.error.isVisible = false
        loadMoreBinding.loading.isVisible = false
        loadMoreBinding.nomore.isVisible = false
    }

    private var isAttachWindow = false

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LoadMoreHolder {
        return LoadMoreHolder(loadMoreBinding.root)
    }

    override fun getItemCount(): Int {
        return 1
    }

    override fun onBindViewHolder(holder: LoadMoreHolder, position: Int) {
    }

    override fun getItemViewType(position: Int): Int {
        return 888
    }

    override fun onViewAttachedToWindow(holder: LoadMoreHolder) {
        super.onViewAttachedToWindow(holder)
        if (!isLoading && !loadMoreEnd) {
            isLoading = true
            onLoadMoreListener?.invoke()
        }
        isAttachWindow = true
    }

    override fun onViewDetachedFromWindow(holder: LoadMoreHolder) {
        super.onViewDetachedFromWindow(holder)
        isAttachWindow = false
    }
}